package com.xckj.cycling.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.mapbox.maps.MapView
import com.xckj.cycling.databinding.LayoutDebugInfoBinding

open class LifecycleMapView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : MapView(context, attrs), DefaultLifecycleObserver {
    private val debugView =
        LayoutDebugInfoBinding.inflate(LayoutInflater.from(requireContext()), this, false)

    init {
        addView(debugView.root)
        debugView.root.bringToFront()
    }

    override fun onStart(owner: LifecycleOwner) {
        super<DefaultLifecycleObserver>.onStart(owner)
        this.onStart()
    }

    override fun onStop(owner: LifecycleOwner) {
        super<DefaultLifecycleObserver>.onStop(owner)
        this.onStop()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super<DefaultLifecycleObserver>.onDestroy(owner)
        this.onDestroy()
    }

    fun requireContext(): Context {
        return context
    }

    fun appendLog(log: String?) {
        log ?: return
        debugView.debug.append(log)
        debugView.debug.append("\r\n")
        debugView.scroll.fullScroll(FOCUS_DOWN)
    }
}